import type { Directive } from "vue";
import defaultStyle from "@/config/defaultConfig";
import { copyText } from "@/utils/copy";
import { showSuccess } from "@/utils/tip/message";

export type CopyDirective = Directive<HTMLElement, string>;

declare module "vue" {
  export interface ComponentCustomProperties {
    vCopy: CopyDirective;
  }
}

declare global {
  interface HTMLElement {
    __handler?: () => void;
  }
}

function createCopyHandler(text: string) {
  return async () => {
    let res = await copyText(text);
    if (res) showSuccess("复制成功！");
  };
}

export default {
  mounted(el, binding) {
    const { blue, green } = binding.modifiers;
    // console.log("mounted: ", blue, green, binding);
    el.style.cursor = "pointer";
    if (blue) el.style.color = defaultStyle.CopyBlue;
    if (green) el.style.color = defaultStyle.CopyGreen;

    el.__handler = createCopyHandler(binding.value);
    el.addEventListener("click", el.__handler);
  },
  updated(el, binding) {
    if (el.__handler) {
      el.removeEventListener("click", el.__handler);
    }
    el.__handler = createCopyHandler(binding.value);
    el.addEventListener("click", el.__handler);
  },
} satisfies CopyDirective;
